/* eslint-disable no-unused-vars */
/* eslint-disable import/no-absolute-path */
import { zoomMap, sourcesMap, baseLayers } from './mapMixinsData';
import { checkLoaded, addSourceMap } from '@/utils/mapUtil';
import { homeChart } from '@/api/mapBase';
let currentZoom = null;
let timeoutIndex = null;
const a = [];
const LevelForZoom = [6.652, 7.9, 9.4];
function getCurZoom (map) {
  timeoutIndex = setTimeout(() => {
    if (!map.isZooming()) {
      currentZoom = map.getZoom();
    } else {
      getCurZoom(map);
    }
  }, 500);
}
function getBounds (arrListA) {
  let [minLng, maxLng, minLat, maxLat] = [180, 0, 90, 0];
  arrListA.map(arrListB => {
    arrListB.map(arrListC => {
      arrListC.map(point => {
        const [lng, lat] = point;
        lng > maxLng && (maxLng = lng);
        lng < minLng && (minLng = lng);
        lat > maxLat && (maxLat = lat);
        lat < minLat && (minLat = lat);
      });
    });
  });
  return [[maxLng, maxLat], [minLng, minLat]];// 右上 左下
}
/**
 * 该mixins用于添加地图的公共功能
 * 1 显示天地图 
 * 2 省边界线/省界面
 * 3 双击聚焦功能
 * 三级 province city district 
 */
// const centerInfo = {};
const tempZoomMap = {};
export default {
  watch: {
    '$store.getters.areaIds': {
      handler (nv, ov) {
        if (nv !== ov) {
          try {
            const areaIdsArr = JSON.parse(nv);
            this.areaChange(areaIdsArr.pop());
            this.areaIdsChange();
          } catch (e) {
            console.error('areaIds 格式有误！');
          }
        }
      },
      immediate: false
    },
    // adcode areaids 获取的时机不同 需要根据依赖情况各自使用
    '$store.getters.adcode': {
      handler (nv, ov) {
        if (nv !== ov) {
          this.adcodeChange();
        }
      },
      immediate: false
    }

  },
  methods: {
    initMap (options) {
      return new Promise((resolve, reject) => {
        checkLoaded(options).then(async (map) => {
          this.map = map;
          process.env.NODE_ENV !== 'production' && (window.map = map);
          await this.addImgSource();// 添加完图片资源再进行加载图层，否则会在图层渲染时找不到图片资源。
          addSourceMap({ map, sources: sourcesMap });
          baseLayers.map((layerInfo) => {
            // map.addLayer(layerInfo);
            const beforeId = layerInfo.beforeId;
            if (beforeId && map.getLayer(beforeId)) {
              map.addLayer(layerInfo, beforeId);
            } else {
              map.addLayer(layerInfo);
            }
          });
          const areaIdsArr = JSON.parse(this.$store.getters.areaIds);
          this.areaChange(areaIdsArr.pop()); // 切换当前区域
          this.addMapEvent();
          resolve(map);
        });
      });
    },
    areaChange (id) {
      const { map } = this;
      homeChart({ id }).then((res) => {
        if (res.code === 200) {
          const { boundary, inner } = res.data;
          map.getSource('focuseBorder').setData(boundary);
          if (inner.features.length === 0) {
            boundary.features[0].properties.nums = boundary.features[0].properties.nums || 0;
            map.getSource('focuseArea').setData(boundary);
          } else {
            map.getSource('focuseArea').setData(inner);
          }
          if (!boundary.features[0]) return;
          const { properties: { id }, geometry } = boundary.features[0];

          // 任务1 定位 缩放
          let bounds = this.$store.getters.boundsMap[id];
          if (!bounds) {
            bounds = getBounds(geometry.coordinates);
            this.$store.commit('pages/SET_BOUNDS', { id, bounds });
          }

          map.fitBounds(bounds, {
            padding: {
              top: 240,
              bottom: 170,
              left: 530,
              right: 530
            }
          });
          // 任务2 为缩放还原准备
          // 地图居中 缩放有个时间 需要
          currentZoom = null;
          getCurZoom(map);
          this.$store.commit('pages/SET_AD_CODE', boundary.features[0].properties.code);
          this.$store.commit('pages/SET_AD_INFO', boundary.features[0].properties);
          // 任务3 准备质心 地区名字

          const targetFeatures = inner.features.length === 0 ? boundary.features : inner.features;
          const focuseAreaNamesFeatures = targetFeatures.map(item => {
            const { lat, lng } = item.properties;
            return {
              type: 'Feature',
              properties: item.properties,
              geometry: {
                coordinates: [lng, lat],
                type: 'Point'

              }
            };
          });
          map.getSource('focuseAreaName').setData({
            features: focuseAreaNamesFeatures,
            type: 'FeatureCollection'
          });
        }
      });
    },
    addImgSource () { },
    // 为地图添加事件
    addMapEvent () {
      this.map.on('dblclick', 'focuseAreaLayer', this.handleFocusArea);
      this.map.on('contextmenu', 'focuseAreaLayer', this.logInfo);
      this.map.on('zoomend', this.handleZoomend);
      this.map.on('dblclick', 'tianditu', this.logInfo);
    },
    // 开发期间信息采集的工具函数
    logInfo (e) {
      // 收集各个区域的放大倍数----------------------------s
      const { id } = e.features[0].properties;
      tempZoomMap[id] = {
        zoom: this.map.getZoom(),
        center: this.map.getCenter()
      };
      a.push(e.lngLat);
      // console.log('zoom:', this.map.getZoom(), 'center', this.map.getCenter());
      console.log('logInfo', JSON.stringify(tempZoomMap));
      // console.log('lngLat', JSON.stringify(a));
      // 收集各个区域的放大倍数----------------------------e

      // 当前zoom center
      // eslint-disable-next-line import/no-absolute-path
    },
    // 变化焦点区域
    handleFocusArea (e) {
      const properties = e.features[0].properties;
      try {
        const areaIdsArr = JSON.parse(this.$store.getters.areaIds);
        areaIdsArr.push(properties.id);
        this.$store.commit('pages/SET_AD_IDS', JSON.stringify(areaIdsArr));
        this.$store.commit('pages/SET_AD_CODE', properties.code);
      } catch (e) {
        console.error('areaIds 格式有误！');
      }
      // this.$store.commit('pages/SET_AD_INFO', properties);
    },
    // 放大级别变化事件
    handleZoomend () {
      if (!currentZoom) return;
      const { map } = this;
      const areaIdsArr = JSON.parse(this.$store.getters.areaIds);
      console.log('zoom changeed...', map.getZoom());
      if (areaIdsArr.length === 1) return;
      if (map.getZoom() < currentZoom - 0.3) {
        areaIdsArr.splice(-1);
        this.$store.commit('pages/SET_AD_IDS', JSON.stringify(areaIdsArr));
      }
    },
    addMaskLayer () { },
    // 焦点区域变化后 更新相应图层的数据
    areaIdsChange () { },
    adcodeChange () { }

  },
  beforeRouteLeave (to, from, next) {
    this.map.remove();// 清理并释放和地图相关的所有内部数据源。包括 DOM 元素，事件绑定，工作线程，和 WebGL 资源。当你使用完地图并希望不再占用浏览器资源时可以使用该方法。之后你将不能在地图上调用任何方法。
  }
};